#!/usr/bin/env python

import os
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext.webapp import template

class MainHandler(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if user:
      passwds = Password.all().filter('user =', user)
      tpl_vars = {
        'passwds': passwds,
        'clear_key_after_each_use': False,
        'logout_url': users.create_logout_url('/logout')
      }
      path = os.path.join(os.path.dirname(__file__), 'main.tpl')
      self.response.out.write(template.render(path, tpl_vars))
    else:
      self.redirect('/login')

class AddHandler(webapp.RequestHandler):
  def post(self):
    user = users.get_current_user()
    if user:
      passwd = Password(
        username = self.request.get('username') or 'None',
        password = self.request.get('password') or 'None',
        link = self.request.get('link') or 'None',
        info = self.request.get('info') or 'None',
        user = user
      )
      passwd.put()
      self.redirect('/')
    else:
      self.redirect('/login')

class DelHandler(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if user:
      key = self.request.get('key')
      db.delete(key)
      self.redirect('/')
    else:
      self.redirect('/login')

class LoginHandler(webapp.RequestHandler):
  def get(self):
    tpl_vars = {
      'login_url': users.create_login_url('/')
    }
    path = os.path.join(os.path.dirname(__file__), 'login.tpl')
    self.response.out.write(template.render(path, tpl_vars))

class LogoutHandler(webapp.RequestHandler):
  def get(self):
    tpl_vars = {
      'login_url': users.create_login_url('/')
    }
    path = os.path.join(os.path.dirname(__file__), 'logout.tpl')
    self.response.out.write(template.render(path, tpl_vars))

class HelpHandler(webapp.RequestHandler):
  def get(self):
    path = os.path.join(os.path.dirname(__file__), 'help.tpl')
    self.response.out.write(template.render(path, {}))

class Password(db.Model):
  username = db.StringProperty(required=True)
  password = db.StringProperty(required=True)
  link = db.StringProperty()
  info = db.StringProperty()
  user = db.UserProperty(required=True)

def main():
  application = webapp.WSGIApplication([
    ('/', MainHandler),
    ('/add', AddHandler),
    ('/del', DelHandler),
    ('/login', LoginHandler),
    ('/logout', LogoutHandler),
    ('/help', HelpHandler)
  ], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
